<template>
    <div class="LoginPage">
        <el-card class="box-card">
            <template #header>
                黑马面经运营后台
            </template>
            <template>
                <el-form class="form" ref="ruleForm" :model="form" :rules="rules" status-icon>
                    <el-form-item label="用户名：" prop="username">
                        <el-input v-model="form.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码：" prop="password">
                        <el-input v-model="form.password" @keydown.native.enter="submitForm('ruleForm')"></el-input>
                    </el-form-item>
                    <div class="btn">
                        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </div>
                </el-form>
            </template>
        </el-card>
    </div>
</template>

<script>
import { Message } from 'element-ui'
import { setToken } from '@/utils/storage'

export default {
    name: 'LoginIndex',
    data () {
        return {
            form: {},
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        submitForm (formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    try {
                        await this.$store.dispatch('user/getLogin', this.form)
                        Message.success('登录成功！')
                        this.$router.push('/')
                    } catch (err) {
                        this.resetForm('ruleForm')
                    }
                    return true
                } else {
                    return false
                }
            })
        },
        resetForm (formName) {
            this.$refs[formName].resetFields()
        }
    }
}
</script>

<style scoped lang="scss">
.LoginPage {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: url(@/assets/login-bg.svg) no-repeat center;
    background-size: cover;


    .box-card {
        width: 420px;
        height: 360px;

        ::v-deep .el-card__header {
            color: white;
            background-color: #727CF5;
            text-align: center;
        }

        .form {
            display: flex;
            flex-direction: column;
            margin: 0 20px;

            .btn {
                align-self: center;
            }
        }
    }
}
</style>
